"""
构建GUI版本的exe文件
Author: AI Assistant
Date: 2025-01-09
"""
import os
import sys
import subprocess
from pathlib import Path

def check_dependencies():
    """检查依赖"""
    print("检查依赖包...")
    
    required_packages = [
        'python-docx',
        'openpyxl', 
        'pandas',
        'requests',
        'lxml',
        'tqdm',
        'Pillow'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
            print(f"+ {package}")
        except ImportError:
            print(f"- {package} 未安装")
            missing_packages.append(package)
    
    if missing_packages:
        print(f"\n需要安装以下包: {', '.join(missing_packages)}")
        return False
    
    print("所有依赖包已安装")
    return True

def install_missing_packages():
    """安装缺失的包"""
    print("安装缺失的依赖包...")
    
    packages = [
        'python-docx',
        'openpyxl', 
        'pandas',
        'requests',
        'lxml',
        'tqdm',
        'Pillow'
    ]
    
    for package in packages:
        try:
            print(f"安装 {package}...")
            subprocess.run([sys.executable, "-m", "pip", "install", package], 
                         check=True, capture_output=True)
            print(f"+ {package} 安装成功")
        except subprocess.CalledProcessError as e:
            print(f"- {package} 安装失败: {e}")
            return False
    
    return True

def build_exe():
    """构建exe文件"""
    print("\n开始构建exe文件...")
    
    # 项目根目录
    project_root = Path(__file__).parent
    os.chdir(project_root)
    
    # PyInstaller命令
    cmd = [
        "pyinstaller",
        "--onefile",
        "--windowed", 
        "--name=实验报告批改系统",
        "--add-data=src;src",
        "--add-data=src/config.json;.",
        "--hidden-import=tkinter",
        "--hidden-import=tkinter.ttk",
        "--hidden-import=tkinter.filedialog",
        "--hidden-import=tkinter.messagebox",
        "--hidden-import=tkinter.scrolledtext",
        "--hidden-import=threading",
        "--hidden-import=json",
        "--hidden-import=pathlib",
        "--hidden-import=datetime",
        "--hidden-import=logging",
        "--hidden-import=collections",
        "src/gui_app.py"
    ]
    
    print(f"执行命令: {' '.join(cmd)}")
    
    try:
        result = subprocess.run(cmd, check=True, capture_output=True, text=True, encoding='utf-8')
        print("构建成功!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"构建失败: {e}")
        if e.stdout:
            print(f"输出: {e.stdout}")
        if e.stderr:
            print(f"错误: {e.stderr}")
        return False
    except FileNotFoundError:
        print("错误: 未找到PyInstaller，请先安装: pip install pyinstaller")
        return False

def main():
    """主函数"""
    print("=" * 60)
    print("实验报告批改系统 - 美化GUI版本构建")
    print("=" * 60)
    
    # 检查依赖
    if not check_dependencies():
        print("\n安装缺失的依赖包...")
        if not install_missing_packages():
            print("依赖安装失败，无法继续构建")
            return False
    
    # 构建exe
    if not build_exe():
        print("构建失败")
        return False
    
    print("\n" + "=" * 60)
    print("构建完成!")
    print("=" * 60)
    print("exe文件位置: dist/实验报告批改系统.exe")
    print("\n使用说明:")
    print("1. 双击运行 '实验报告批改系统.exe'")
    print("2. 在美化界面中配置输入输出目录")
    print("3. 设置API密钥和模型参数")
    print("4. 点击'🚀 开始批改'按钮")
    print("5. 享受现代化的用户体验!")
    print("=" * 60)
    
    return True

if __name__ == "__main__":
    success = main()
    if not success:
        sys.exit(1)
